export function useTouchSwipe(options = {}) {
  const {
    threshold = 0.2, // 滑动阈值（20%）
    maxIndex = 0, // 最大索引
    onIndexChange = null // 索引变化回调
  } = options

  const touchState = reactive({
    startY: 0,
    currentY: 0,
    isSwiping: false,
    currentIndex: 0,
    offset: 0
  })

  const start = (event) => {

    touchState.startY = event.touches[0].clientY
    touchState.currentY = touchState.startY
    touchState.isSwiping = true
    touchState.offset = 0
  }

  const move = (event) => {

    if (!touchState.isSwiping) return

    touchState.currentY = event.touches[0].clientY
    const deltaY = touchState.currentY - touchState.startY
    touchState.offset = deltaY

    // 阻止边界外的滑动
    if ((touchState.currentIndex === 0 && deltaY > 0) ||
      (touchState.currentIndex === unref(maxIndex) && deltaY < 0)) {
      touchState.offset = deltaY * 0.3 // 边界阻力效果
    }
  }

  const end = () => {

    if (!touchState.isSwiping) return

    touchState.isSwiping = false
    const deltaY = touchState.currentY - touchState.startY
    const deltaRatio = Math.abs(deltaY) / window.innerHeight

    if (deltaRatio > threshold) {
      // 滑动距离足够，切换视频
      const newIndex = deltaY > 0
        ? Math.max(0, touchState.currentIndex - 1)
        : Math.min(unref(maxIndex), touchState.currentIndex + 1)

      touchState.currentIndex = newIndex
      if (onIndexChange) onIndexChange(newIndex)
    }

    // 重置偏移量
    touchState.offset = 0
  }

  const getTransform = () => {
    const baseTransform = touchState.currentIndex * -100
    const offsetPercent = (touchState.offset / window.innerHeight) * 100
    return `translateY(calc(${baseTransform}% + ${offsetPercent}%))`
  }

  return {
    touchState,
    start,
    move,
    end,
    getTransform,
    setCurrentIndex: (index) => {
      touchState.currentIndex = index
    },
    currentIndex: computed(() => touchState.currentIndex)
  }
}